//#pragma once
#ifndef SERIALIZER_H__
#define SERIALIZER_H__
#include "base64.h"
template<typename TObj>
class Serializer
{
public:
	static std::string ToString(const TObj& rObj)
	{
		std::string sEncodeString;
		Base64::Encode((const unsigned char *)(&rObj),sizeof(TObj),sEncodeString);
		return sEncodeString;
	}
	static void FromString(TObj& rObj,std::string& sValue)
	{
		if(sValue.empty()) return;
		Base64::Decode( sValue,(unsigned char *)(&rObj) );
	}
};

class DataStream
{
public:
	DataStream()
		:m_size(0)
		,m_wp(0)
		,m_rp(0)
		,m_pData(NULL)
	{

	}
	~DataStream()
	{
		if(m_pData)
		{
			free(m_pData);
			m_pData=NULL;
		}
	}

	void Write(void * pData,uint32 iSize)
	{
		if(iSize+m_wp>m_size)
		{
			More((iSize+m_wp)*2);
		}
		memcpy_s(m_pData+m_wp,m_size-m_wp,pData,iSize);
		m_wp+=iSize;
	}

	template <class T>
	void Write(const T& data)
	{
		Write((void*)&data,sizeof(data));
	}

	bool Read(void *pData,uint32 iSize)
	{
		if(iSize==0) return true;
		if(iSize+m_rp>m_wp) return false;
		memcpy_s(pData,iSize,m_pData+m_rp,iSize);
		m_rp+=iSize;
		return true;
	}

	template <class T>
	bool  Read(T& data)
	{
		return Read(&data,sizeof(data));
	}

	uint32 Len() const
	{
		return m_wp;
	}
	void * Data() const { return m_pData;}

	bool IsReadEnd() const { return m_rp>=m_wp;}

private:
	void More(uint32 iSize)
	{
		char* pNew=(char*)::malloc(iSize);
		memcpy_s(pNew,iSize,m_pData,m_size);

		m_size=iSize;
		::free(m_pData);
		m_pData=pNew;
	}
	uint32 m_wp;
	uint32 m_rp;
	uint32 m_size;
	char *m_pData;
};
inline void UtilWriteString(DataStream& ds,const std::string& sValue)
{
	ds.Write(sValue.size());
	ds.Write((void*)sValue.c_str(),sValue.size());
}
inline std::string UtilReadString(DataStream& ds)
{
	uint32 iSize=0;
	ds.Read(iSize);
	char * pBuffer=new char[iSize+1];
	ds.Read(pBuffer,iSize);
	std::string sRet(pBuffer,iSize);
	delete[] pBuffer;
	return sRet;
}


#endif
